<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace yiike\user\controllers;

use Yii;
use yiike\user\models\Token;
use common\helpers\CommonHelper;
use common\models\LoginForm;
use yiike\user\models\Account;

/**
 * Description of RegisterController
 *
 * @author Administrator
 */
class LoginController extends \api\components\Controller {

    public $clients = [
        'qq'        => [
            'class'        => 'yiike\user\clients\Qq',
            'clientId'     => '1105710365', //1105319535 ios  1105237062 android
            'name'         => 'qq',
            'clientSecret' => '',
        ],
        'weixin'    => [
            'class'        => 'yiike\wechat\authclient\WechatApp',
            'clientId'     => 'wx6187dd451c922522', //wxdbf2e3a38c77bd38
            'clientSecret' => '2066fc28b70f5b3deb6765a09c3393fd', //9e7fa0078473180a014ea6c90285e2c6
        ],
        'wechat-mp' => [
            'class' => 'yiike\wechat\authclient\WechatMp',
        ],
        'mobile'    => [
            'class' => 'yiike\user\clients\Mobile',
        ]
    ];

    /**
     * @inheritdoc
     */
    public function behaviors() {
        return [
            'verbs' => [
                'class'   => \yii\filters\VerbFilter::className(),
                'actions' => [
                    'index' => ['post'],
                ],
            ],
        ];
    }

    public function actionIndex() {
        $login    = Yii::$app->request->post('login');
        $password = Yii::$app->request->post('password');

        $loginForm = Yii::createObject(LoginForm::className());
        $loginForm->setAttributes([
            'login'    => $login,
            'password' => $password
        ]);

        if ($loginForm->login()) {

            $user    = Yii::$app->user->identity;
            $profile = $user->profile;
            $token   = Yii::createObject(['class' => Token::className(), 'type' => Token::TYPE_LOGIN]);
            $token->link('user', $user);

            return ['code' => 0, 'message' => '登录成功', 'username' => $user->username, 'name' => $profile->name, 'avatar' => $profile->avatarUrl, 'token' => $token->code];
        }
        else {
            return ['code' => 100029, 'message' => CommonHelper::arrayToString($loginForm->errors)];
        }
    }

    public function actionAuth() {
        $authclient = Yii::$app->request->get('authclient');
        $params     = Yii::$app->request->get('params');
        if (is_string($params)) {
            $params = json_decode($params, true);
        }
        if (!$authclient || !$params) {
            return ['code' => 100039];
        }

        try {
            $client  = $this->getClient($authclient, $params);
            $account = Account::find()->byClient($client)->one();
        }
        catch (\yii\base\Exception $e) {
            return ['code' => $e->getCode()];
        }

        if ($account === null) {
            $account    = Account::create($client);
            $attributes = $client->getUserAttributes();
            $profile = $account->user->profile;
            if (isset($attributes['name'])) {
                $profile->setAttribute('name', $attributes['name']);
            }
            if (isset($attributes['avatar'])) {
                $profile->setAvatarByUrl($attributes['avatar']);
            }
            $profile->update();
        }

        if ($account->user instanceof \dektrium\user\models\User) {
            $user    = $account->user;
            $profile = $user->profile;
            $token   = Yii::createObject(['class' => Token::className(), 'type' => Token::TYPE_LOGIN, 'client' => $authclient]);
            $token->link('user', $user);

            return ['code' => 0, 'message' => '登录成功', 'user_id' => $user->id, 'username' => $user->username, 'name' => $profile->name, 'avatar' => $profile->avatarUrl, 'token' => $token->code];
        }
        else {
            return ['code' => 100029, 'message' => CommonHelper::arrayToString($account->errors)];
        }
    }

    /**
     * Runs the action.
     */
    public function getClient($clientId, $params) {
        $this->clients[$clientId] += $params;

        $client = Yii::createObject($this->clients[$clientId]);

        return $client;
    }

}
